package cn.corffen.test.algorithm.leetcode.binarytree;

import com.corffen.libsource.Queue;
import com.corffen.libsource.StdRandom;
import com.corffen.libsource.TreeNode;
import javafx.util.Pair;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class BinaryTreeDemo {

    public static void main(String[] args) {
//        printPreOrder();

//        printLevelBottom();
//        printSortedArr2BST();

//        printLevelBottom();
//        printInvertTree();
        printHasPath();
    }

    /**
     * 2
     * / \
     * 0   3
     * /     \
     * 1      4
     */
    private static void printSortedArr2BST() {
        int[] arr = new int[5];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i;
        }
        TreeNode node1 = sortedArr2BST(arr);
        System.out.println("前序遍历:");
        printTreeNode(preorderTraversal(node1));
        System.out.println("中序遍历:");
        printTreeNode(inOrderTraversal(node1));
        System.out.println("后序遍历-->递归:");
        printTreeNode(postOrderTraversal(node1));
        System.out.println("后序遍历-->迭代:");
        printTreeNode(postOrderTraversal2(node1));
        System.out.println("层级遍历-->");
        printTreeNode(levelTraversal(node1));
    }

    private static void printLevelBottom() {
        TreeNode root = generateTreeNode();
        System.out.println("二叉树:");
        System.out.println(levelTraversal(root).toString());
        List<List<Integer>> result = levelOrderBottom(root);
        System.out.println("层级从下至上");
        System.out.println(Arrays.deepToString(result.toArray()));
        System.out.println("最小深度为:" + minDepth(root));
    }

    private static void printHasPath() {
        TreeNode root = generateTreeNode();
        System.out.println("二叉树:");
        System.out.println(levelTraversal(root).toString());
//        System.out.println("使用递归:");
//        System.out.println("存在路径:" + hasPathSum(root, 13));
        System.out.println("使用迭代:");
        System.out.println("存在路径:" + hasPathSumWithBFS(root, 13));
    }

    private static void printInvertTree() {
        TreeNode root = generateTreeNode();
        System.out.println("二叉树:之前");
        System.out.println(levelTraversal(root).toString());
        invertTree(root);
        System.out.println("翻转后");
        System.out.println(levelTraversal(root).toString());
    }


    private static void printPreOrder() {
//        TreeNode node1 = printBinaryTree();
//        printTreeNode(levelTraversal(node1));

        Integer[] arr = generateArr(20);
        System.out.println("原数组" + Arrays.toString(arr));
        Integer[] result = arrToMinHeap(arr);
        System.out.println("二叉堆:" + Arrays.toString(result));
    }

    private static Integer[] generateArr(int n) {
        Integer[] arr = new Integer[n];
        for (int i = 0; i < n; i++) {
            arr[i] = i;
        }
        StdRandom.shuffle(arr);
        return arr;
    }

    private static void printTreeDepth() {
        TreeNode node = generateTreeNode();
        System.out.println("递归 node 深度:" + maxDepthWithTraversal(node));
        System.out.println("迭代 node 深度:" + maxDepthWithLoop(node));
    }

    private static TreeNode printBinaryTree() {
        TreeNode node1 = generateTreeNode();

        System.out.println("node1 是否对称:" + isSymmetric(node1));

//        System.out.println(preorderTraversal(node1).toString());
//        System.out.println("node isBalance:" + isBalanced(node1));
        System.out.println("前序遍历:");
        printTreeNode(preorderTraversal(node1));
        System.out.println("中序遍历:");
        printTreeNode(inOrderTraversal(node1));
        System.out.println("后序遍历-->递归:");
        printTreeNode(postOrderTraversal(node1));
        System.out.println("后序遍历-->迭代:");
        printTreeNode(postOrderTraversal2(node1));
        System.out.println("层级遍历-->");
        printTreeNode(levelTraversal(node1));
        return node1;
    }

    private static void printTreeNode(List<Integer> list) {
        System.out.println(list.toString());
    }

    /**
     * 6
     * /
     * 4
     * / \
     * 2   5
     * / \
     * 1   3
     *
     * @return 二叉树
     */
    private static TreeNode generateTreeNode() {
        TreeNode node1 = new TreeNode(6);
        TreeNode node2 = new TreeNode(4);
        TreeNode node3 = new TreeNode(2);
        TreeNode node4 = new TreeNode(1);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(3);

        node1.left = node2;
        node2.left = node3;
        node2.right = node5;
        node3.left = node4;
        node3.right = node6;
        return node1;
    }


    /**
     * 前序遍历 的顺序是 根---左---右
     * 思路:
     * 1.先将根节点入栈
     * 2.出栈一个元素,将右节点和左节点依次入栈
     * 3.重复2的步骤
     * <p>
     * 宏观角度来看就是自顶向下依次访问左侧链,然后自底向上依次访问右侧链.
     *
     * @param root 二叉树
     * @return 返回访问的顺序.
     */
    public static List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> v = new ArrayList<>();
        LinkedList<TreeNode> s = new LinkedList<>();
        while (root != null || !s.isEmpty()) {
            while (root != null) {
                v.add(root.val);
                s.push(root);
                root = root.left;
            }
            root = s.pop().right;
        }
        return v;
    }

    /**
     * 前序遍历递归
     *
     * @param root
     * @return
     */
    public List<Integer> preorderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        preorder(root, res);
        return res;
    }

    public void preorder(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }
        list.add(root.val);
        preorder(root.left, list);
        preorder(root.right, list);
    }

    /**
     * 中序遍历
     * 遍历顺序是 左---根---右
     * 思路:
     * 1.根节点入栈
     * 2.判断有没有左节点,如果有,就入栈,直到叶子结点
     * 3.出栈,判断有没有右结点,有则入栈,继续执行2
     *
     * @param root
     * @return
     */
    public static List<Integer> inOrderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        inOrder(root, res);
        return res;
    }

    /**
     * 中序遍历
     * 遍历顺序是 左---根---右
     * 思路:
     * 1.根节点入栈
     * 2.判断有没有左节点,如果有,就入栈,直到叶子结点
     * 3.出栈,判断有没有右结点,有则入栈,继续执行2
     *
     * @param root
     * @return
     */
    public static List<Integer> inOrderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        LinkedList<TreeNode> stack = new LinkedList<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }

    public static void inOrder(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }
        inOrder(root.left, list);
        list.add(root.val);
        inOrder(root.right, list);
    }

    public static List<Integer> postOrderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        postOrder(root, res);
        return res;
    }

    public static void postOrder(TreeNode root, List<Integer> list) {
        if (root != null) {
            postOrder(root.left, list);
            postOrder(root.right, list);
            list.add(root.val);
        }
    }

    /**
     * 后序遍历:
     * 顺序是左---右---根
     *
     * @param root
     * @return
     */
    public static List<Integer> postOrderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        LinkedList<TreeNode> stack = new LinkedList<>();
        if (root == null) {
            return res;
        }

        TreeNode current;
        TreeNode last;
        current = root;
        last = root;
        while (current != null) {
            stack.push(current);
            current = current.left;
        }

        while (!stack.isEmpty()) {
            current = stack.pop();
            if (current.right != null && current.right != last) {
                stack.push(current);
                current = current.right;
                while (current != null) {
                    stack.push(current);
                    current = current.left;
                }
            } else {
                res.add(current.val);
                last = current;
            }
        }
        return res;
    }

    public static List<Integer> levelTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Queue<TreeNode> queue = new Queue<>();
        queue.enqueue(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.dequeue();
            if (node == null) {
                continue;
            }
            res.add(node.val);
            queue.enqueue(node.left);
            queue.enqueue(node.right);
        }
        return res;
    }


    public static boolean isBalanced(TreeNode root) {
        return recur(root) != -1;
    }

    public static int recur(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = recur(root.left);
        if (left == -1) {
            return -1;
        }
        int right = recur(root.right);
        if (right == -1) {
            return -1;
        }
        return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1;
    }


    /**
     * 判断二叉树是否是对称的
     *
     * @param root 二叉树
     * @return 如果是对称的就返回true, 否则false
     */
    public static boolean isSymmetric(TreeNode root) {

        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        queue.add(root);
        TreeNode t1, t2;
        while (!queue.isEmpty()) {
            t1 = queue.poll();
            t2 = queue.poll();
            if (t1 == null && t2 == null) {
                continue;
            }
            if (t1 == null || t2 == null) {
                return false;
            }
            if (t1.val != t2.val) {
                return false;
            }
            queue.add(t1.left);
            queue.add(t2.right);
            queue.add(t1.right);
            queue.add(t2.left);
        }
        return true;
    }

    public static boolean isSymmetricWithTraversal(TreeNode root) {
        return isSymmetric(root, root);
    }

    private static boolean isSymmetric(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }
        return p.val == q.val && isSymmetric(p.left, q.right) && isSymmetric(p.right, q.left);
    }

    public static Integer[] arrToMinHeap(Integer[] arr) {
        int n = arr.length;
        Integer[] pq = new Integer[n + 1];
        for (int i = 0; i < n; i++) {
            pq[i + 1] = arr[i];
        }
        for (int k = n / 2; k >= 1; k--) {
            while (k * 2 <= n) {
                int j = 2 * k;
                if (j < n && pq[j] > pq[j + 1]) {
                    j = j + 1;
                }
                if (pq[k] <= pq[j]) {
                    break;
                }
                int temp = pq[k];
                pq[k] = pq[j];
                pq[j] = temp;
                k = j;
            }
        }
        return pq;
    }

    /**
     * 递归判断两个二叉树是否相等
     *
     * @param p
     * @param q
     * @return
     */
    public static boolean isSameTeeWithTraversal(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }
        return p.val == q.val && isSameTeeWithTraversal(p.left, q.left) && isSameTeeWithTraversal(p.right, q.right);
    }

    /**
     * 使用level 遍历,比较每一个结点是否相等
     *
     * @param p
     * @param q
     * @return
     */
    public static boolean isSameTreeWithLoop(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }

        if (!checkSame(p, q)) {
            return false;
        }

        LinkedList<TreeNode> queueP = new LinkedList<>();
        LinkedList<TreeNode> queueQ = new LinkedList<>();
        queueP.add(p);
        queueQ.add(q);
        while (!queueP.isEmpty()) {
            p = queueP.poll();
            q = queueQ.poll();
            if (!checkSame(p, q)) {
                return false;
            }
            if (p != null) {
                if (!checkSame(p.left, q.left)) {
                    return false;
                }
                if (p.left != null) {
                    queueP.add(p.left);
                    queueQ.add(q.left);
                }

                if (!checkSame(p.right, q.right)) {
                    return false;
                }
                if (p.right != null) {
                    queueP.add(p.right);
                    queueQ.add(q.right);
                }
            }
        }
        return true;
    }

    private static boolean checkSame(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }

        return p.val == q.val;
    }

    public static int maxDepthWithTraversal(TreeNode root) {
        if (root == null) {
            return 0;
        } else {
            int leftHeight = maxDepthWithTraversal(root.left);
            int rightHeight = maxDepthWithTraversal(root.right);
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }

    public static int maxDepthWithLoop(TreeNode root) {
        if (root == null) {
            return 0;
        }
        LinkedList<Pair<TreeNode, Integer>> queue = new LinkedList<>();
        queue.add(new Pair<>(root, 1));
        int depth = 0;
        Pair<TreeNode, Integer> current;
        while (!queue.isEmpty()) {
            current = queue.poll();
            root = current.getKey();
            Integer currentDepth = current.getValue();
            if (root != null) {
                depth = Math.max(depth, currentDepth);
                queue.add(new Pair<>(root.left, currentDepth + 1));
                queue.add(new Pair<>(root.right, currentDepth + 1));
            }
        }
        return depth;
    }

    public static List<List<Integer>> levelOrderBottom(TreeNode root) {
        LinkedList<List<Integer>> result = new LinkedList<>();
        if (root == null) {
            return result;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int count = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < count; i++) {
                root = queue.poll();
                list.add(root.val);
                if (root.left != null) {
                    queue.add(root.left);
                }
                if (root.right != null) {
                    queue.add(root.right);
                }
            }
            result.addFirst(list);
        }
        return result;
    }

    public static TreeNode sortedArr2BST(int[] arr) {
        return helper(arr, 0, arr.length - 1);
    }

    private static TreeNode helper(int[] nums, int left, int right) {
        if (left > right) {
            return null;
        }
        int mid = (left + right) / 2;
        //每次都选取中间位置的数 作为父结点
        TreeNode root = new TreeNode(nums[mid]);
        root.left = helper(nums, left, mid - 1);
        root.right = helper(nums, mid + 1, right);

        return root;
    }

    public static int minDepth(TreeNode root) {
        LinkedList<Pair<TreeNode, Integer>> queue = new LinkedList<>();
        if (root == null) {
            return 0;
        } else {
            queue.add(new Pair<TreeNode, Integer>(root, 1));
        }

        int min = Integer.MAX_VALUE;
        while (!queue.isEmpty()) {
            Pair<TreeNode, Integer> pair = queue.poll();
            root = pair.getKey();
            int current_min = pair.getValue();
            if (root.left == null && root.right == null) {
                min = Math.min(min, current_min);
                return min;
            }
            if (root.left != null) {
                queue.add(new Pair<>(root.left, current_min + 1));
            }

            if (root.right != null) {
                queue.add(new Pair<>(root.right, current_min + 1));
            }
        }
        return min;
    }

    public static int minDepthWithOutPair(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return 0;
        } else {
            queue.add(root);
        }
        int result = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                root = queue.poll();
                if (root.left == null && root.right == null) {
                    return result;
                }
                if (root.left != null) {
                    queue.add(root.left);
                }
                if (root.right != null) {
                    queue.add(root.right);
                }
            }
            result++;
        }
        return result;
    }

    public static int minDepthWithRecursion(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = minDepthWithRecursion(root.left);
        int right = minDepthWithRecursion(root.right);
        if (left != 0 && right != 0) {
            return 1 + Math.min(left, right);
        }
        return left + right + 1;
    }

    public static TreeNode invertTree(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return null;
        } else {
            queue.add(root);
        }
        while (!queue.isEmpty()) {
            TreeNode current = queue.poll();
            TreeNode temp = current.left;
            current.left = current.right;
            current.right = temp;
            if (current.left != null) {
                queue.add(current.left);
            }
            if (current.right != null) {
                queue.add(current.right);
            }
        }
        return root;
    }

    /**
     * 给定一个二叉树和一个目标和，判断该树中是否存在根节点到叶子节点的路径，这条路径上所有节点值相加等于目标和。
     *
     * @param root 二叉树
     * @param sum  目标之和
     * @return
     */
    public static boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }
        sum -= root.val;
        if (root.left == null && root.right == null) {
            return sum == 0;
        }
        return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
    }

    public static boolean hasPathSumWithBFS(TreeNode root, int sum) {
        LinkedList<TreeNode> stack = new LinkedList<>();
        LinkedList<Integer> sumStack = new LinkedList<>();
        if (root == null) {
            return false;
        } else {
            stack.add(root);
            sumStack.add(sum - root.val);
        }
        int currentSum;
        TreeNode current;
        while (!stack.isEmpty()) {
            current = stack.pollLast();
            currentSum = sumStack.pollLast();

            if (current.left == null && current.right == null && currentSum == 0) {
                return true;
            }

            if (current.left != null) {
                stack.add(current.left);
                sumStack.add(currentSum - current.left.val);
            }

            if (current.right != null) {
                stack.add(current.right);
                sumStack.add(currentSum - current.right.val);
            }
        }
        return false;
    }

    /**
     *            10
     *         5     15
     *       3  7       18
     */
}
